import axios from "axios";
import store from "@/store";
import { MessageBox, Message } from "element-ui";
import { getToken } from "@/utils/auth";
// 在当前模块中引入store

const requests = axios.create({
  baseURL: "/api",
  // baseURL: "https://yfjx.online",
  timeout: 50000,
});
// axios.defaults.headers = {
//     'Content-type': 'application/x-www-form-urlencoded'
// }
function toLogin() {
  //  const vueinstance=  getCurrentInstance();
  if (window.location.hash) {
    window.location.href = window.location.origin + "/login";
    return;
  }
  window.location.href = window.location.origin + "/login";
  //  router.push({ path: '/login', params: { r: Math.random() } });
}
requests.interceptors.request.use(
  (config) => {
    // nProgress.start();
    // if (
    //   config.url.indexOf("/basic-authentication") != -1 &&
    //   config.url != "/basic-authentication/route/info"
    // ) {
    //   return config;
    // }
    // if (
    //   config.url == "/business-personnel/sms/send_sms" ||
    //   config.url == "/business-personnel/user/update_password"
    // ) {
    //   return config;
    // }
    console.log("requests");
    if (getToken("token")) {
      console.log(getToken("token"), 1);
      config.headers["token"] = getToken("token");
    }
    // const token = localStorage.getItem("token");
    // if (token) {
    //   console.log(token, 1);
    //   config.headers["token"] = token;
    // }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

requests.interceptors.response.use(
  (res) => {
    console.log("response1", res, res.data.resultCode);
    // nProgress.done();
    if (res.data && res.data.resultCode == 401) {
      console.log("登陆已过期", Message);
      // Message.error("登陆已过期");
      // Message.error({
      //   showClose: true,
      //   message: "登陆已过期",
      //   type: "error",
      // });
      // this.$router.push(`/login`);
      MessageBox.confirm("登陆已过期，您可以取消以留在此页面，或重新登录", {
        confirmButtonText: "重新登录",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        store.dispatch("logout").then(() => {
          console.log("res-resetToken");
          location.reload();
        });
      });
      return;
    }
    return res.data;
  },
  (error) => {
    console.log("response2", error);
    return Promise.reject(new Error("faile"));
  }
);

export default requests;
